#!/bin/bash
# 获取脚本所在目录
DIRNAME=$(cd "$(dirname "$0")"; pwd)

# 定义工作空间路径（项目根目录）
# 原理：取脚本目录的上级目录，兼容软链接场景
WORKSPACE=$(dirname "$DIRNAME")
[ -z "$WORKSPACE" ] && echo "错误: 工作空间路径解析失败" && exit 1

# 检查依赖工具
check_dependencies() {
  local missing=()
  ! command -v jq &> /dev/null && missing+=("jq")
  ! command -v java &> /dev/null && missing+=("Java")

  if [ ${#missing[@]} -gt 0 ]; then
    echo "缺失依赖: ${missing[*]}"
    echo "请先安装jq工具: brew install jq (macOS) 或 apt-get install jq (Linux)"
    exit 1
  fi
}

read_config() {
  # 参数校验段
  if [ $# -lt 3 ]; then
    echo "Usage: $0 <channel> <apkPath> <productFlavor>"
    exit 1
  fi
  CHANNEL="$1"
  TARGET_APK="$2"
  PRODUCT_FLAVOR="$3"

  # 环境检测段
  [ -z "$ANDROID_HOME" ] && echo "ERROR: ANDROID_HOME not set" && exit 1
  [ -z "$WORKSPACE" ] && echo "ERROR: WORKSPACE not set" && exit 1

  # 工具路径配置
  BUILD_TOOLS="$ANDROID_HOME/build-tools/30.0.2"
  
  # 配置文件检测
  CONFIG_FILE="$WORKSPACE/buildsystem/apksigner_configs.json"
  [ ! -f "$CONFIG_FILE" ] && echo "ERROR: Missing config file $CONFIG_FILE" && exit 1

  # 新增：检查PRODUCT_FLAVOR是否存在配置中
  if ! jq -e ".${PRODUCT_FLAVOR}" "$CONFIG_FILE" > /dev/null; then
    echo "ERROR: 请检查apksigner_configs.json配置是否正确，未找到'${PRODUCT_FLAVOR}'对应的配置"
    exit 1
  fi

  # 使用jq解析JSON配置
  CONFIG_DIR=$(dirname "$CONFIG_FILE")
  RAW_KEYSTORE_PATH=$(jq -r ".${PRODUCT_FLAVOR}.ks_path" "$CONFIG_FILE")
  KEY_ALIAS=$(jq -r ".${PRODUCT_FLAVOR}.ks_alias" "$CONFIG_FILE")
  KEYSTORE_PASS=$(jq -r ".${PRODUCT_FLAVOR}.ks_pwd" "$CONFIG_FILE")

  # 密钥路径解析（相对CONFIG_FILE所在目录）
  if [[ "$RAW_KEYSTORE_PATH" =~ ^\.\./.* ]]; then
    # 处理../开头的相对路径
    KEYSTORE_PATH="${CONFIG_DIR%/*}/${RAW_KEYSTORE_PATH#../}"
  elif [[ "$RAW_KEYSTORE_PATH" =~ ^\./.* ]]; then
    # 处理./开头的相对路径
    KEYSTORE_PATH="${CONFIG_DIR}/${RAW_KEYSTORE_PATH#./}"
  else
    # 处理无前缀的相对路径
    KEYSTORE_PATH="${CONFIG_DIR}/${RAW_KEYSTORE_PATH}"
  fi

  # 参数验证
  [ -z "$KEY_ALIAS" ] && echo "ERROR: Failed to get key alias" && exit 1
  [ -z "$KEYSTORE_PASS" ] && echo "ERROR: Failed to get keystore password" && exit 1
  [ ! -f "$KEYSTORE_PATH" ] && echo "ERROR: Keystore not found at $KEYSTORE_PATH" && exit 1
}


# 主流程
main() {
  check_dependencies
  read_config "$@"  # 传递所有命令行参数

  # 提取APK名称
  TARGET_APK_NAME=$(basename "$TARGET_APK" .apk)
  OUT_DIR="${DIRNAME}/output"
  mkdir -p "$OUT_DIR"

  echo "=============== 配置信息 ================"
  echo "构建工具: $BUILD_TOOLS"
  echo "目标APK: $TARGET_APK"
  echo "渠道   : $CHANNEL"
  echo "输出目录: $OUT_DIR"
  echo "密钥库  : $KEYSTORE_PATH"
  echo "密钥别名: $KEY_ALIAS"
  echo "========================================"

  # zipalign处理
  echo "=============== zipalign处理 ============="
  "${BUILD_TOOLS}/zipalign" -v -p 4 "$TARGET_APK" "${TARGET_APK_NAME}-aligned.apk"

  # apksigner签名（兼容Windows/macOS/Linux）
  echo "=============== apksigner签名 ============"
  APKSIGNER_CMD="apksigner"
  if [[ "$OSTYPE" == "msys" ]]; then
    APKSIGNER_CMD="apksigner.bat"
  fi

  "${BUILD_TOOLS}/${APKSIGNER_CMD}" sign \
    --v1-signing-enabled true \
    --v2-signing-enabled true \
    --ks "$KEYSTORE_PATH" \
    --ks-key-alias "$KEY_ALIAS" \
    --ks-pass "pass:$KEYSTORE_PASS" \
    --key-pass "pass:$KEYSTORE_PASS" \
    --out "${TARGET_APK_NAME}-signed.apk" \
    "${TARGET_APK_NAME}-aligned.apk"
  sleep 3  # 确保签名完成

  # VasDolly渠道写入
  echo "=============== VasDolly渠道写入 ========="
  OUT_DIR="${OUT_DIR%/}"  # 移除尾部斜杠
  java -jar "${DIRNAME}/VasDolly.jar" put -c "$CHANNEL" \
    "${TARGET_APK_NAME}-signed.apk" "${OUT_DIR}"

  # 清理临时文件
  echo "=============== 清理临时文件 ============="
  rm -f "${TARGET_APK_NAME}-aligned.apk" "${TARGET_APK_NAME}-signed.apk" *.idsig

  echo "=============== 处理完成 ================="
  echo "已签名并打包渠道的APK保存在: ${OUT_DIR}/"
}

main "$@"  # 执行主函数并传递所有参数